package jgcp.common.network;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.Socket;
import java.net.UnknownHostException;
/**
 * 
 * @Date 29/05/2009
 * @author Jie Zhao (288654)
 * @version 1.0
 * @param <T>
 */
public class FileReceiver<T extends Serializable> extends Thread {
	private String host;
	private int port = 0;
	private String tempFile = "";
	private T resultObj = null;
	
	public FileReceiver(String hostname, int port,String tempfile) {
		host = hostname;
		this.port = port;
		this.tempFile = tempfile;
	}
	
	public T getObject()
	{
		return resultObj;
	}
	
@Override
public void run() {
	try {
		System.out.println("Task receiver started on port:"+port);
		Socket s = new Socket(host,port);
		File file = new File(tempFile);
		if(!file.exists())
		{
			file.createNewFile();
		}
		InputStream is = s.getInputStream();
		//read object
		ObjectInputStream ois = new ObjectInputStream(is);
		resultObj = (T)ois.readObject();
		//read file
		FileOutputStream fos = new FileOutputStream(file);
		byte[] buffer = new byte[65534];
		System.out.println("start receive.");
		while(true)
		{
			int length = is.read(buffer);
			if(length == -1)break;
			fos.write(buffer, 0, length);
		}
		System.out.println("Receive end");
		fos.flush();
		fos.close();
		is.close();
		s.close();
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
}
}
